var express = require('express');
var jwt = require("jsonwebtoken");
var router = express.Router();
const { User, Category, Medicine, orderModel, Delivery, gouModel, jiaModel, diModel } = require('../model/db')


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 登录接口
router.post('/login', async (req, res) => {
    let data = await User.findOne(req.body)
    if(data){
      let token = jwt.sign({userId:data._id},'166822Liu');
      res.send({
        code:200,
        msg:'ok',
        data:data,
        token:token
      })
      
    }else{
      res.send({
        code:403,
        msg:'账号或密码错误'
      })
    }
});
// 注册接口
router.post('/register', async (req, res) => {
    if(!req.body.username || !req.body.password || !req.body.phone){
      res.send({
        code:403,
        msg:'请填写完整信息'
      })
      return
    }
    console.log(req.body);
    
    let data = await User.findOne({phone:req.body.phone}) // 查找数据库中是否有该用户
    if(data){
      res.send({
        code:403,
        msg:'该用户已存在'
      })
    }else{
      let data = await User.create(req.body) // 如果没有该用户，则创建该用户
      res.send({
        code:200,
        msg:'ok',
        data:data
      }) 
    }
})
// 药品分类列表路由
router.get('/categories', async (req, res) => {
  try {
    const categories = await Category.find();
    res.status(200).json({ message: '药品分类列表获取成功', categories });
  } catch (error) {
    res.status(500).json({ message: '药品分类列表获取失败', error });
  }
});

// 药品列表路由
router.get('/medicines', async (req, res) => {
  try {
    const medicines = await Medicine.find();
    res.status(200).json({ message: '药品列表获取成功', medicines });
  } catch (error) {
    res.status(500).json({ message: '药品列表获取失败', error });
  }
});

// 订单创建路由
// router.post('/orders', async (req, res) => {
//   try {
//     const { userId, medicines, totalPrice, status } = req.body;
//     const order = new Order({ userId, medicines, totalPrice, status });
//     await order.save();
//     res.status(201).json({ message: '订单创建成功', order });
//   } catch (error) {
//     res.status(500).json({ message: '订单创建失败', error });
//   }
// });

// 订单列表路由
// router.get('/orders', async (req, res) => {
//   try {
//     const orders = await Order.find();
//     res.status(200).json({ message: '订单列表获取成功', orders });
//   } catch (error) {
//     res.status(500).json({ message: '订单列表获取失败', error });
//   }
// });

// 订单详情路由
// router.get('/orders/:orderId', async (req, res) => {
//   try {
//     const orderId = req.params.orderId;
//     const order = await Order.findById(orderId);
//     if (!order) {
//       return res.status(404).json({ message: '订单不存在' });
//     }
//     res.status(200).json({ message: '订单详情获取成功', order });
//   } catch (error) {
//     res.status(500).json({ message: '订单详情获取失败', error });
//   }
// });

// 订单更新路由
// router.put('/orders/:orderId', async (req, res) => {
//   try {
//     const orderId = req.params.orderId;
//     const { status } = req.body;
//     const order = await Order.findByIdAndUpdate(orderId, { status }, { new: true });
//     if (!order) {
//       return res.status(404).json({ message: '订单不存在' });
//     }
//     res.status(200).json({ message: '订单更新成功', order });
//   } catch (error) {
//     res.status(500).json({ message: '订单更新失败', error });
//   }
// });


// 订单删除路由
// router.delete('/orders/:orderId', async (req, res) => {
//   try {
//     const orderId = req.params.orderId;
//     const order = await Order.findByIdAndDelete(orderId);
//     if (!order) {
//       return res.status(404).json({ message: '订单不存在' });
//     }
//     res.status(200).json({ message: '订单删除成功', order });
//   } catch (error) {
//     res.status(500).json({ message: '订单删除失败', error });
//   }
// });

// 配送创建路由
router.post('/deliveries', async (req, res) => {
  try {
    const { orderId, address, status } = req.body;
    const delivery = new Delivery({ orderId, address, status });
    await delivery.save();
    res.status(201).json({ message: '配送创建成功', delivery });
  } catch (error) {
    res.status(500).json({ message: '配送创建失败', error });
  }
});

// 配送列表路由
router.get('/deliveries', async (req, res) => {
  try {
    const deliveries = await Delivery.find();
    res.status(200).json({ message: '配送列表获取成功', deliveries });
  } catch (error) {
    res.status(500).json({ message: '配送列表获取失败', error });
  }
});

// 配送详情路由
router.get('/deliveries/:deliveryId', async (req, res) => {
  try {
    const deliveryId = req.params.deliveryId;
    const delivery = await Delivery.findById(deliveryId);
    if (!delivery) {
      return res.status(404).json({ message: '配送不存在' });
    }
    res.status(200).json({ message: '配送详情获取成功', delivery });
  } catch (error) {
    res.status(500).json({ message: '配送详情获取失败', error });
  }
});

// 配送更新路由
router.put('/deliveries/:deliveryId', async (req, res) => {
  try {
    const deliveryId = req.params.deliveryId;
    const { address, status } = req.body;
    const delivery = await Delivery.findByIdAndUpdate(deliveryId, { address, status }, { new: true });
    if (!delivery) {
      return res.status(404).json({ message: '配送不存在' });
    }
    res.status(200).json({ message: '配送更新成功', delivery });
  } catch (error) {
    res.status(500).json({ message: '配送更新失败', error });
  }
});

// 配送删除路由
router.delete('/deliveries/:deliveryId', async (req, res) => {
  try {
    const deliveryId = req.params.deliveryId;
    const delivery = await Delivery.findByIdAndDelete(deliveryId);
    if (!delivery) {
      return res.status(404).json({ message: '配送不存在' });
    }
    res.status(200).json({ message: '配送删除成功', delivery });
  } catch (error) {
    res.status(500).json({ message: '配送删除失败', error });
  }
});

// 购物车列表
router.get("/list", async function (req, res, next) {
  const list = await gouModel.find();
  res.send({
    list,
    code: 200,
  });
});

router.get("/list1", async function (req, res, next) {
  const list1 = await jiaModel.find();
  res.send({
    list1,
    code: 200,
  });
});

// 删除商品路由
router.delete("/list/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const result = await gouModel.findByIdAndDelete(id);
    if (result) {
      res.send({
        code: 200,
        message: "删除成功",
      });
    } else {
      res.status(404).send({
        code: 404,
        message: "商品不存在",
      });
    }
  } catch (error) {
    console.error("删除失败:", error);
    res.status(500).send({
      code: 500,
      message: "删除失败",
    });
  }
});
router.get("/list3", async function (req, res, next) {
  const list2 = await diModel.find();
  res.send({
    list2,
    code: 200,
  });
});
// 添加地址
router.post("/add", async function (req, res, next) {
  await diModel.create(req.body);
  res.send({
    msg: "添加成功",
    code: 200,
  });
});
// 修改地址
router.put("/update", async (req, res) => {
  try {
    let { _id } = req.body;
    if (!_id) {
      return res.status(400).send({
        code: 400,
        message: "缺少 _id 参数",
      });
    }
    const result = await diModel.updateOne({ _id }, req.body);
    if (result.nModified === 0) {
      return res.status(404).send({
        code: 404,
        message: "未找到要更新的记录",
      });
    }
    res.send({
      code: 200,
      message: "更新成功",
    });
  } catch (error) {
    console.error("更新失败:", error);
    res.status(500).send({
      code: 500,
      message: "更新失败: " + error.message,
    });
  }
});
// 删除地址
router.delete("/del", async (req, res) => {
  let { _id } = req.query;
  await diModel.deleteOne({ _id });
  res.send({
    code: 200,
  });
});

// 引入腾讯云人脸识别包
let tencentcloud = require("tencentcloud-sdk-nodejs-iai");
// 人脸识别后端
router.post("/faceLogin", async function (req, res) {
  const base64 = req.body.base64;
  if (!base64) {
    return res.json({
      code: -2,
      msg: "前端未传递图片，请检查请求数据",
    });
  }
  const IaiClient = tencentcloud.iai.v20200303.Client;
  const clientConfig = {
    credential: {
      // secretId:'AKIDolhZGl8SdqZCyeLp6Azax72jCxZy96tU',
      // secretKey:'RdcQ0MVQ7aqwoRq44sSr31lHbibHm5A1',
      secretId:'AKIDSlqhOr55sTr0wjWBvb7PUM0QdeR0LTN3',
      secretKey:'UlqurjeWG1d2DH8lANN9gz5xb1EEC3iO'
    },
    region: "ap-beijing",
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };
  const client = new IaiClient(clientConfig);
  const params = {
    GroupIds: ["001"],
    Image: base64,
    NeedPersonInfo: 1,
    QualityControl: 0,
    FaceMatchThreshold: 85,
  };
  try {
    const { Results } = await client.SearchFaces(params);
    if (Results[0].Candidates.length === 0) {
      res.json({
        code: -1,
        msg: "该人员没有注册",
      });
      return;
    }
    const { FaceId, Gender, PersonId, PersonName } = Results[0].Candidates[0];
    res.json({
      code: 0,
      data: {
        FaceId,
        Gender,
        PersonId,
        PersonName,
      },
      msg: "识别成功",
    });
  } catch (error) {
    console.error("人脸识别请求出错:", error);
    res.json({
      code: -1,
      msg: "人脸识别请求出错，请稍后重试",
    });
  }
})

// const serverRouter = express();
// serverRouter.use(cors());
// serverRouter.use(express.json());

const API_KEY = 'sk-5b12d9d303744b538e105eab4849762c';
router.post('/generate-image', async (req, res) => {
    console.log('Received request:', req.body);
  try {
    const response = await axios.post(
      'https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis',
      {
        model: 'wanx-v1',
        input: { prompt: req.body.prompt }
      },
      {
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json',
          'X-DashScope-Async':'enable'
        }
      }
    );
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// module.exports = serverRouter;
// const Core = require('@alicloud/pop-core');

// // 从环境变量获取阿里云的 AccessKey ID 和 AccessKey Secret
// const client = new Core({
//   accessKeyId: '22095485',
//   accessKeySecret: 'sk-5b12d9d303744b538e105eab4849762c',
//   endpoint: 'https://dashscope.cn-shanghai.aliyuncs.com',
//   apiVersion: '2024 - 01 - 11'
// });

// // 验证阿里云密钥是否存在
// if (!client.accessKeyId || !client.accessKeySecret) {
//   console.error('阿里云 AccessKey ID 或 AccessKey Secret 未配置，请检查 .env 文件');
// }

// // 定义实际的 AI 绘画服务调用函数
// async function callAIDrawService(prompt) {
//   // 验证 prompt 参数
//   if (!prompt || typeof prompt !== 'string' || prompt.trim().length === 0) {
//     throw new Error('绘画描述信息无效，请提供有效的文本描述');
//   }

//   const params = {
//     "Model": "qwen - turbo - vision",
//     "Input": {
//       "messages": [
//         {
//           "role": "user",
//           "content": [
//             {
//               "type": "text",
//               "text": `请根据以下描述生成一张图片：${prompt.trim()}`
//             }
//           ]
//         }
//       ]
//     },
//     "Parameters": {
//       "image_generation": {
//         "width": 1024,
//         "height": 1024,
//         "num_images": 1
//       }
//     }
//   };

//   const requestOption = {
//     method: 'POST'
//   };

//   try {
//     const response = await client.request('Invoke', params, requestOption);
//     if (response.Output && response.Output.choices && response.Output.choices[0].message && response.Output.choices[0].message.content && response.Output.choices[0].message.content[0].image_url) {
//       return { imageUrl: response.Output.choices[0].message.content[0].image_url };
//     } else {
//       throw new Error('阿里云响应数据格式不正确');
//     }
//   } catch (error) {
//     console.error('阿里云请求出错:', error);
//     throw error;
//   }
// }

// const API_KEY1 = 'sk-5b12d9d303744b538e105eab4849762c';

router.get('/check-task/:taskId', async (req, res) => {
  try {
    const response = await axios.get(
      `https://dashscope.aliyuncs.com/api/v1/tasks/${req.params.taskId}`,
      {
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );
    res.json(response.data);
  } catch (error) {
    console.error('检查任务状态失败:', error);
    res.status(500).json({ error: error.message });
  }
});

// 订单相关================================
router.get("/wm", async (req, res) => {
  let sj = await wmModel.find();
  res.send({ code: 200, sj });
});

router.get("/pl", async (req, res) => {
  let sj = await plModel.find();
  res.send({ code: 200, sj });
});

router.get("/fl", async (req, res) => {
  let sj = await flModel.find();
  res.send({ code: 200, sj });
});

// 获取所有订单
router.get("/orders", async (req, res) => {
  try {
    const orders = await orderModel.find();
    console.log(orders);
    res.send({ code: 200, msg: "获取订单成功", data: orders });
  } catch (e) {
    console.error("error", e);
    res.send({ code: 500, msg: "获取订单失败", error: e.message });
  }
});

// 删除订单
router.delete("/order/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const deletedOrder = await orderModel.findOneAndDelete({ id });
    if (!deletedOrder) {
      return res.status(404).send({ code: 404, msg: "订单不存在" });
    }
    res.send({ code: 200, msg: "订单已删除" });
  } catch (e) {
    console.log("删除订单异常:", e);
    res.status(500).send({ code: 500, msg: "服务器内部错误" });
  }
});

// 获取单个订单详情
router.get("/order/:id", async (req, res) => {
  try {
    const order = await orderModel.findOne({ id: req.params.id });
    if (!order) return res.send({ code: 404, msg: "订单不存在" });
    res.send({ code: 200, data: order });
  } catch (e) {
    res.send({ code: 500, msg: "获取订单详情失败" });
  }
});

// 更新订单状态
router.post("/order/:id/status", async (req, res) => {
  try {
    const { status: newStatus } = req.body;
    const { id } = req.params;

    const order = await orderModel.findOne({ id });

    if (!order) {
      return res.status(404).send({ code: 404, msg: "订单不存在" });
    }

    // 支付操作校验：只有待付款(pending)的订单才能变为待收货(delivering)
    if (newStatus === "delivering" && order.status !== "pending") {
      return res.status(400).send({ code: 400, msg: "订单状态异常，无法支付" });
    }

    // 状态映射
    const statusTextMap = {
      pending: "待付款",
      delivering: "待收货",
      finished: "已完成",
      cancel: "订单已取消",
    };
    const statusText = statusTextMap[newStatus] || order.statusText;

    const updatedOrder = await orderModel.findOneAndUpdate(
      { id },
      { status: newStatus, statusText },
      { new: true }
    );

    res.send({ code: 200, data: updatedOrder });
  } catch (e) {
    console.log("订单状态更新异常:", e);
    res.status(500).send({ code: 500, msg: "服务器内部错误" });
  }
});

// [Admin] 获取所有待支付订单
router.get("/admin/pending-orders", async (req, res) => {
  try {
    const pendingOrders = await orderModel
      .find({ status: "pending" })
      .sort({ orderTime: -1 });
    res.send({ code: 200, data: pendingOrders });
  } catch (e) {
    console.log("获取待支付订单异常:", e);
    res.status(500).send({ code: 500, msg: "服务器内部错误" });
  }
});



module.exports = router;
